package com.alks.entity.data.i18n;

import cn.hutool.extra.spring.SpringUtil;
import com.alibaba.excel.util.StringUtils;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializerProvider;
import org.springframework.context.i18n.LocaleContextHolder;

import java.io.IOException;
import java.util.*;

public class TranslateFieldSerializer extends JsonSerializer<Object> {
    
    private String language;

    private TranslateService service;

    public TranslateFieldSerializer() {
        this.service = SpringUtil.getBean(TranslateService.class);
    }

    @Override
    public void serialize(Object value, JsonGenerator gen, SerializerProvider serializers) throws IOException {
        Object translatedValue = translateRecursively(value);
        Map<String, Object> result = new HashMap<>();
        result.put("key", value);
        result.put("value", translatedValue);
        gen.writeObject(result);
    }

    /**
     * 递归处理对象：如果是 String 执行翻译；如果是 List 则递归处理其内容；
     * 否则直接返回原值
     */
    private Object translateRecursively(Object obj) {
        if (obj instanceof String) {
            return translateString((String) obj);
        } else if (obj instanceof List) {
            List<?> list = (List<?>) obj;
            List<Object> translatedList = new ArrayList<>();
            for (Object item : list) {
                translatedList.add(translateRecursively(item));
            }
            return translatedList;
        } else {
            return obj;
        }
    }

    /**
     * 翻译字符串逻辑：提取中文、调用翻译服务
     */
    private String translateString(String text) {
        String chineseOnly = extractChinese(text);
        Locale locale = LocaleContextHolder.getLocale();
        String language = locale.getLanguage();
        String translation;

        if (!chineseOnly.isEmpty()) {
            translation = service.translate(chineseOnly, language);
        } else {
            translation = service.translate(text, language);
        }
        String replace = text;
        if (StringUtils.isBlank(translation)) {
            translation = text;
        }else {
            replace = text.replace(chineseOnly, translation);
        }
        return !chineseOnly.isEmpty() ? replace : translation;
    }

    /**
     * 提取出字符串中的中文部分
     */
    private String extractChinese(String text) {
        StringBuilder chineseOnly = new StringBuilder();
        for (char c : text.toCharArray()) {
            if (isChinese(c)) {
                chineseOnly.append(c);
            }
        }
        return chineseOnly.toString();
    }

    /**
     * 判断字符是否为中文
     */
    private boolean isChinese(char c) {
        return c >= '\u4e00' && c <= '\u9fff';
    }

}